<template>
    <div class="login">
        <Particles id="tsparticles" class="login__particles" :options="options" />

        <div class="loginPart">
            <h2>找回账号</h2>
            <el-form :model="forgetForm" ref="forgetFormRef" :rules="rules" label-width="100px"
                style="transform: translate(-30px)">
                <el-form-item label="账号" prop="username">
                    <el-input v-model="forgetForm.username" placeholder="请输入账号" clearable></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="forgetForm.phone" placeholder="请输入注册时的手机号" clearable></el-input>
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                    <el-input type="password" v-model="forgetForm.newPassword" placeholder="请输入新密码" show-password
                        clearable></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                    <el-input type="password" v-model="forgetForm.confirmPassword" placeholder="请确认新密码" show-password
                        clearable></el-input>
                </el-form-item>

                <el-button class="btn" type="primary" :loading="isLoading" @click="handleReset">重置密码</el-button>
                <div style="text-align: right; transform: translate(0, 30px)">
                    <el-link type="primary" @click="goToLogin">返回登录</el-link>
                </div>
            </el-form>
        </div>
    </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from '@/utils/http'
import qs from 'qs'
import '../components/UserLogin.scss'

// 路由实例
const router = useRouter()

// 表单数据
const forgetForm = reactive({
    username: '',
    phone: '',
    newPassword: '',
    confirmPassword: ''
})

// 表单引用
const forgetFormRef = ref(null)

// 加载状态
const isLoading = ref(false)

// 表单验证规则
const rules = {
    username: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                const usernamePattern = /^[\u4e00-\u9fa5a-zA-Z0-9]{2,6}$/
                if (!value || usernamePattern.test(value)) {
                    callback()
                } else {
                    callback(new Error('账号格式不正确（2-6位的中文、数字或字母组合）'))
                }
            },
            trigger: ['blur', 'change']
        }
    ],
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: ['blur', 'change'] }
    ],
    newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度应在6到20个字符之间', trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'))
                } else if (value !== forgetForm.newPassword) {
                    callback(new Error('两次密码不一致'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ]
}

// 重置密码处理
const handleReset = async () => {
    try {
        isLoading.value = true
        await forgetFormRef.value.validate()

        const requestData = {
            username: forgetForm.username,
            phone: forgetForm.phone,
            new_password: forgetForm.newPassword,
            confirm_password: forgetForm.confirmPassword
        }

        const res = await axios.post('/reset_password/', qs.stringify(requestData), {
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        })
        console.log('前端重置密码请求数据:', requestData)
        console.log('res.data:', res.data)
        if (res.data.code === 200) {
            ElMessage.success('密码重置成功')
            router.push('/login')
        } else {
            ElMessage.error(res.data.message)
        }
    } catch (error) {
        if (error.response) {
            ElMessage.error(error.response.data.message)
        } else {
            ElMessage.error('请求失败，请稍后重试')
        }
        console.error('重置密码失败:', error)
    } finally {
        isLoading.value = false
    }
}

// 返回登录页
const goToLogin = () => {
    router.push('/login')
}

// 粒子效果配置
const options = {
    fpsLimit: 60,
    interactivity: {
        detectsOn: 'canvas',
        events: {
            onClick: {
                enable: true,
                mode: 'push'
            },
            onHover: {
                enable: true,
                mode: 'grab'
            },
            resize: true
        },
        modes: {
            bubble: {
                distance: 400,
                duration: 2,
                opacity: 0.8,
                size: 40
            },
            push: {
                quantity: 4
            },
            grab: {
                distance: 200,
                duration: 0.4
            },
            attract: {
                distance: 200,
                duration: 0.4,
                factor: 5
            }
        }
    },
    particles: {
        color: {
            value: '#BA55D3'
        },
        links: {
            color: '#FFBBFF',
            distance: 150,
            enable: true,
            opacity: 0.4,
            width: 1.2
        },
        collisions: {
            enable: true
        },
        move: {
            attract: { enable: false, rotateX: 600, rotateY: 1200 },
            bounce: false,
            direction: 'none',
            enable: true,
            out_mode: 'out',
            random: false,
            speed: 0.5,
            straight: false
        },
        number: {
            density: {
                enable: true,
                value_area: 800
            },
            value: 80
        },
        opacity: {
            value: 0.7
        },
        shape: {
            type: 'star'
        },
        size: {
            random: true,
            value: 3
        }
    },
    detectRetina: true
}
</script>